//
//  SEGSubmitUserAtuhViewController.m
//  ExcellentHome
//
//  Created by Chiang on 16/8/9.
//  Copyright © 2016年 陈区. All rights reserved.
//
#import "SEGCommunityBuildListModel.h"

#import "SEGFangHaoListViewController.h"
#import "SEGLouDongListViewController.h"
#import "SEGDanYuanListViewController.h"
#import "SEGSubmitUserAtuhViewController.h"

#import "SEGNewAlertView.h"

#import "SEGSubmitUserAuthViewCell.h"

#import "SEGDigitalCommunity2TenantViewModel.h"//人工审核 、 获取类型 提交审核
#import "SEGDataPickerView.h"


static const CGFloat bottomButtonHeight = 40.0;

@interface SEGSubmitUserAtuhViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIAlertViewDelegate, SEGNewAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *secHeaderView;
@property (nonatomic, strong) UIView *phoneHeaderView;
@property (nonatomic, strong) UIView *alertbgView;
/** 申请人姓名 */
@property (nonatomic, strong) UITextField *proposerName;
/** 预留手机号 */
@property (nonatomic, strong) UITextField *proposerPhone;
/** 预留姓名 */
@property (nonatomic, strong) UITextField *name;
/** 预留手机号 */
@property (nonatomic, strong) UITextField *phone;
/** 加载图片 */
@property (nonatomic, strong) UIImageView *loadingImgView;

@property(nonatomic, strong) SEGSubmitUserAtuhViewModel *viewModel;
@property (nonatomic, strong) SEGDigitalCommunity2TenantViewModel *tenantViewModel;

@end

@implementation SEGSubmitUserAtuhViewController
#pragma mark - life cycle
- (instancetype)initWithViewModel:(SEGSubmitUserAtuhViewModel*)viewModel{
    if (self == [super init]) {
        _viewModel = viewModel;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请认证";
    [self showCustomNavigationBackButton];
    [self showCustomNavigationRightButtonWithTitle:@"提交" image:nil hightlightImage:nil color:kColor_1];
    [self.view addSubview:self.tableView];
    // 自助认证
    if (!self.viewModel.isManual) [self addManualApproveLabelInBottom];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveSelectedHouseInfoNotification:)
                                                 name:SEGSelectedHouseInfoNotification
                                               object:nil];
    
    [self segInitViews];
    [self bindViewModel];
    [self bindTenantViewModel];//获取住户类型、发送人工审核接口
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - SEGNewAlertViewDelegate
- (void)segNewAlertView:(UIView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 101) {//失败
        switch (buttonIndex) {
            case 0: {
                break;
            }
            case 1: {
                //                [self.viewModel.userAuthorFailCommand execute:nil];
                //                [SVProgressHUD show];
                //跳转到人工审核页面
                [self seg_pushToSubmitFailUserAuthVC];
                break;
            }
            default:
                break;
        }
    } else if (alertView.tag == 102){
        //自动刷新用户信息
        [self.viewModel.freshProfileCommand execute:nil];
        [SVProgressHUD show];
    }
}



- (void)seg_pushToSubmitFailUserAuthVC {
    SEGSubmitUserAtuhViewModel *submitUserAtuhViewModel = [[SEGSubmitUserAtuhViewModel alloc] init];
    submitUserAtuhViewModel.isManual = YES;
    submitUserAtuhViewModel.buidingModel = self.viewModel.buidingModel;
    submitUserAtuhViewModel.unitModel = self.viewModel.unitModel;
    submitUserAtuhViewModel.houseModel = self.viewModel.houseModel;
    
    SEGSubmitUserAtuhViewController *vc = [[SEGSubmitUserAtuhViewController alloc] initWithViewModel:submitUserAtuhViewModel];
    submitUserAtuhViewModel.proposerNameString = self.proposerName.text;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return self.viewModel.isManual ? 2:3;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) return 1;
    if (self.viewModel.isManual) {
        if (section == 1) {
            return 3;
        }
    }
    return 2;
}
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section {
    return 38.f;
}
- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    if (indexPath.section == 0) {
        return UITableViewAutomaticDimension;
    }
    return 44.0;
}
- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 38)];
    headView.backgroundColor = kColor_bg;
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, LYScreenWidth() - 30, 33)];
    titleLab.font = kFont_13;
    titleLab.textColor = kColor_3;
    if (section == 0) {
        titleLab.text = @"请选择所需认证的房号";
    }else if (section == 1) {
        if (self.viewModel.isManual) {
            titleLab.text = @"请填写您的个人信息";
        }else {
            titleLab.text = @"请填写认证房间的业主/租赁人资料";
        }
        
    } else if (section == 2) {
        titleLab.text = @"请填写您的个人信息";
    }
    [headView addSubview:titleLab];
    return headView;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    if (indexPath.section == 0) {
        SEGSubmitUserAuthViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSubmitUserAuthViewCellIdentifier forIndexPath:indexPath];
        if (self.viewModel.buidingModel.name.length > 0 && self.viewModel.houseModel.roomNo.length > 0) {
            NSString *text = [NSString stringWithFormat:@"%@%@%@", self.viewModel.buidingModel.name, self.viewModel.unitModel.unit, self.viewModel.houseModel.roomNo];
            [cell setHouseInfoText:text];
        }else {
            [cell setHouseInfoText:@""];
        }
        return cell;
    }else if (self.viewModel.isManual && indexPath.row == 2) {
        //选择住户类型
        SEGSubmitUserAuthViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSubmitUserAuthViewCellIdentifier forIndexPath:indexPath];
        cell.userType = self.tenantViewModel.userType;
        return cell;
        
    }else {
        SEGSubmitUserAtuhViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SEGSubmitUserAtuhViewTableViewCell" forIndexPath:indexPath];
        cell.downLine.hidden = YES;
        cell.titleTF.userInteractionEnabled = YES;
        cell.titleTF.returnKeyType = UIReturnKeyDone;
        cell.titleTF.keyboardType = UIKeyboardTypeDefault;
        cell.titleLabel.textColor = kColor_1;
        if (indexPath.section == 2||(self.viewModel.isManual && indexPath.section == 1)) {
            if (indexPath.row == 0) {
                cell.titleLabel.text = @"姓名";
                cell.titleLabel.textColor = kColor_1;
                cell.titleTF.textColor = kColor_1;
                cell.downLine.hidden = NO;
                self.proposerName = cell.titleTF;
                self.proposerName.delegate = self;
                self.proposerName.placeholder = @"将用于缴费/报单功能，请准确填写";
                [self.proposerName setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:self.proposerName.placeholder attributes:@{NSForegroundColorAttributeName:kColor_C}]];
                self.proposerName.text = self.viewModel.proposerNameString;
            }else if (indexPath.row == 1) {
                cell.titleLabel.text = @"手机号";
                self.proposerPhone = cell.titleTF;
                self.proposerPhone.delegate = self;
                self.proposerPhone.textAlignment = NSTextAlignmentRight;
                self.proposerPhone.userInteractionEnabled = NO;
                self.proposerPhone.textColor = kColor_3;
                self.proposerPhone.text = kAccountMobile;
                if (self.viewModel.isManual) {
                    cell.downLine.hidden = NO;
                }
            }
        }else {
            if (indexPath.row == 0) {
                cell.titleLabel.text = @"姓名";
                cell.downLine.hidden = NO;
                self.name = cell.titleTF;
                self.name.textColor = kColor_1;
                self.name.font = kFont_16;
                self.name.delegate = self;
                self.name.returnKeyType = UIReturnKeyDone;
                self.name.placeholder = @"请填写房间业主/租赁人姓名";
                [self.name setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:_name.placeholder attributes:@{NSForegroundColorAttributeName:kColor_C}]];
                self.name.text = self.viewModel.nameString;
            }else if (indexPath.row == 1) {
                cell.titleLabel.text = @"手机号";
                self.phone = cell.titleTF;
                self.phone.font = kFont_16;
                self.phone.delegate = self;
                self.phone.keyboardType = UIKeyboardTypeNumberPad;
                self.phone.textAlignment = NSTextAlignmentRight;
                self.phone.placeholder = @"请填写业主/租赁人手机号";
                [self.phone setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:_phone.placeholder attributes:@{NSForegroundColorAttributeName:kColor_C}]];
                self.phone.textColor = kColor_1;
                self.phone.text = self.viewModel.phoneString;
            }
        }
        return cell;
    }
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
        SEGLouDongListViewModel *vm = [[SEGLouDongListViewModel alloc] init];
        
        if (self.viewModel.buidingModel) {
            vm.selectedModel = self.viewModel.buidingModel;
        }
        if (self.viewModel.unitModel) {
            vm.unitModel = self.viewModel.unitModel;
        }
        if (self.viewModel.houseModel) {
            vm.houseModel = self.viewModel.houseModel;
        }
        
        SEGLouDongListViewController* myProfileViewCtl = [[SEGLouDongListViewController alloc] initWithViewModel:vm];
        myProfileViewCtl.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:myProfileViewCtl animated:YES];
    }
    if (self.viewModel.isManual && indexPath.section == 1 && indexPath.row == 2) {
        //选择 住户类型
        [self.view endEditing:YES];
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
        NSMutableArray *dataArray = [NSMutableArray new];
        
        [[self.tenantViewModel.userTypeCommand execute:nil] subscribeNext:^(id  _Nullable x) {
            for (NSString *name in self.tenantViewModel.userTypeArr) {
                [dataArray addObject:@{@"data":[NSString stringWithFormat:@"%lu",(unsigned long)[self.tenantViewModel.userTypeArr indexOfObject:name]],@"desc":name,@"select":@([self.tenantViewModel.userType isEqualToString:name])}];
            }
            if (dataArray.count > 0) {
                [SEGDataPickerView showWithTitle:@"选择住户类型" data:@[dataArray] pickerBlock:^(NSDictionary * _Nullable params) {
                    if ([[params allKeys] containsObject:@"component_0"]) {
                        NSDictionary *dicElevator = [params valueForKey:@"component_0"];
                        self.tenantViewModel.userType = [dicElevator valueForKey:@"desc"];
                        [self.tableView reloadData];
                    }
                }];
            }else {
                [SEGAlertView showTmepMessageWithMessage:@"暂无数据"];
            }
        } error:^(NSError * _Nullable error) {
            [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        }];
        
        
        
        
        
    }
}

#pragma mark - 选择房屋信息后
- (void)didReceiveSelectedHouseInfoNotification:(NSNotification *)notification {
    NSDictionary *dic = notification.object;
    self.viewModel.buidingModel = dic[@"buildModel"];
    self.viewModel.unitModel = dic[@"unitModel"];
    self.viewModel.houseModel = dic[@"houseModel"];
    [self.tableView reloadData];
}

#pragma mark scrollDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView {
    [_phone resignFirstResponder];
}

#pragma mark textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField {
    CGRect parentRect = [textField convertRect:textField.bounds toView:self.tableView];
    if (parentRect.origin.y > 100) {
        [self.tableView setContentOffset:CGPointMake(0, parentRect.origin.y - 100) animated:YES];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.name) {
        self.viewModel.nameString = textField.text;
    }else if (textField == self.phone) {
        self.viewModel.phoneString = textField.text;
    }else if (textField == self.proposerPhone) {
        self.viewModel.proposerPhoneString = textField.text;
    }else if (textField == self.proposerName) {
        self.viewModel.proposerNameString = textField.text;
    }
}

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == self.proposerName) {
        self.viewModel.proposerNameString = text;
    }
    if (range.length == 1 && [string isEqualToString:@""]) { //退格键
        return YES;
    }
    if (textField == self.phone) {
        if (text.length > 11)  return NO;
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField {
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [textField resignFirstResponder];
    return YES;
}

- (UITableView*)tableView {
    if (_tableView == nil) {
        CGFloat bottomPadding = self.viewModel.isManual ? 0 :bottomButtonHeight;
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight() - kNavigationBarAndStatusBarHeight - bottomPadding  - LYSafeAreaBottom()) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = kColor_bg;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorColor = kColor_L2;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.estimatedRowHeight = 44;
        [_tableView registerClass:[SEGSubmitUserAtuhViewTableViewCell class] forCellReuseIdentifier:@"SEGSubmitUserAtuhViewTableViewCell"];
        [_tableView registerClass:[SEGSubmitUserAuthViewCell class] forCellReuseIdentifier:kSubmitUserAuthViewCellIdentifier];
    }
    return _tableView;
}

- (void)checkAlertView {
    if (_alertbgView == nil) {
        _alertbgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight())];
        _alertbgView.backgroundColor = [kColor_1 colorWithAlphaComponent:0.6];
        
        UIView* boxView = [[UIImageView alloc] initWithFrame:CGRectMake((LYScreenWidth() - 240) / 2, (LYScreenHeight() - 144) / 2, 240, 144)];
        boxView.layer.cornerRadius = 4;
        boxView.backgroundColor = kColor_W;
        [_alertbgView addSubview:boxView];
        
        UIImage* image = [UIImage imageWithContentsOfFile:SEGPicName(@"bg_loading")];
        _loadingImgView = [[UIImageView alloc] initWithFrame:CGRectMake((240 - image.size.width) / 2, 36, image.size.width, image.size.height)];
        _loadingImgView.image = image;
        [boxView addSubview:_loadingImgView];
        
        UILabel* desc = [[UILabel alloc] initWithFrame:CGRectMake(20, 59 + image.size.height, 200, 15)];
        desc.font = [UIFont systemFontOfSize:16];
        desc.textAlignment = NSTextAlignmentCenter;
        desc.textColor = kColor_1;
        desc.text = @"信息匹配中，请稍等...";
        [boxView addSubview:desc];
    }
    
    [[UIApplication sharedApplication].keyWindow addSubview:_alertbgView];
    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
    rotationAnimation.duration = 1;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = FLT_MAX;
    [_loadingImgView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
    WeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.alertbgView removeFromSuperview];
    });
}


/**
 底部添加提交人工审核按钮，方便没有信息的业主审核
 */
-(void)addManualApproveLabelInBottom {
    UIButton *manualApproveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    manualApproveButton.frame=CGRectMake(0, LYScreenHeight() - kNavigationBarAndStatusBarHeight - bottomButtonHeight - LYSafeAreaBottom(), LYScreenWidth(), bottomButtonHeight);
    manualApproveButton.titleLabel.font=kFont_11;
    [manualApproveButton addTarget:self action:@selector(manualApproveTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:manualApproveButton];
    manualApproveButton.backgroundColor = self.tableView.backgroundColor;
    
    NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:kColor_3};
    NSDictionary *dictAttr2 = @{NSForegroundColorAttributeName:kColor_S3};//,NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)
    NSMutableAttributedString *attributedStr1=[[NSMutableAttributedString alloc] initWithString:@"不知道业主信息？" attributes:dictAttr1];
    NSMutableAttributedString *attributedStr2=[[NSMutableAttributedString alloc] initWithString:@"提交人工审核" attributes:dictAttr2];
    [attributedStr1 appendAttributedString:attributedStr2];
    [manualApproveButton setAttributedTitle:attributedStr1 forState:UIControlStateNormal];
}

/**
 点击提交人工审核手势时间
 */
-(void)manualApproveTap {
    [self seg_pushToSubmitFailUserAuthVC];
}

#pragma mark - Init Views
-(void)segInitViews{}

#pragma mark - Layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
}

#pragma mark - Private Methods
- (void)onNavigationRightButtonClicked:(UIButton*)sender {
    [self.tableView endEditing:YES];
    
    self.viewModel.proposerNameString =self.proposerName.text;
    self.viewModel.proposerPhoneString =self.proposerPhone.text;
    self.viewModel.nameString =self.name.text;
    self.viewModel.phoneString =self.phone.text;
    self.viewModel.userTypeCode = [self.tenantViewModel getUserTypeCode];
    
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    
    [self.view endEditing:YES];// 不管输入合不合法，键盘下去 table 滑动回去
    if ([self.viewModel checkSubmitData]) {
        [self.viewModel.userAuthorCommand execute:nil];
        [SVProgressHUD show];
    }
}

#pragma mark - RAC Data Binding
- (void)bindTenantViewModel {
    self.tenantViewModel = [[SEGDigitalCommunity2TenantViewModel alloc] init];
    [self.tenantViewModel.userTypeCommand execute:nil];
    
    [self.tenantViewModel.messageSubject subscribeNext:^(NSDictionary*  _Nullable x) {
        [SVProgressHUD dismiss];
        
        NSString *type = [x valueForKey:@"type"];
        if (!type) return;
        NSString *value = [x valueForKey:@"value"];
        
        if ([type isEqualToString:@"1"]) [SVProgressHUD showWithStatus:value];
        if ([type isEqualToString:@"2"]) [SVProgressHUD showErrorWithStatus:value];
        if ([type isEqualToString:@"3"]) [SVProgressHUD showSuccessWithStatus:value];
    }];
}

- (void)bindViewModel {
    @weakify(self);
    
    [self.viewModel.messageDataSubject subscribeNext:^(NSDictionary *  _Nullable x) {
        
        @strongify(self);
        
        [SVProgressHUD dismiss];
        
        [self.alertbgView removeFromSuperview];
        
        if ([[x valueForKey:@"type"] isEqualToString:@"1"] ) {
            [SEGAlertView showTmepMessageWithMessage:[x valueForKey:@"value"]];
            return;
        }
        
        if ([[x valueForKey:@"type"] isEqualToString:@"2"] ) {
            SEGNewAlertView *alertView = [[SEGNewAlertView alloc] init];
            alertView.delegate = self;
            alertView.tag = 102;
            [alertView showWithAlertTitle:@"自助认证审核成功"
                                     text:@""
                                 delegate:self
                        buttonTitlesArray:@[@"确定"]];
            return;
        }
        
        if ([[x valueForKey:@"type"] isEqualToString:@"3"] ) {
            SEGNewAlertView *alertView = [[SEGNewAlertView alloc] init];
            alertView.delegate = self;
            alertView.tag = 101;
            [alertView showWithAlertTitle:@"验证失败"
                                     text:@"抱歉，您的申请信息与预留在管理处的信息不一致，未通过系统验证！"
                                 delegate:self
                        buttonTitlesArray:@[@"重填",@"人工审核"]];
            return;
        }
    }];
    
    [[[self.viewModel.userAuthorCommand executionSignals] switchToLatest] subscribeNext:^(NSNumber*  _Nullable x) {
        
        @strongify(self);
        
        [SVProgressHUD dismiss];
        
        if ([x integerValue] == 1) {
            //跳出申请认证界面
            NSArray *viewControllers = self.navigationController.viewControllers;
            NSUInteger index = viewControllers.count - 2;
            for (NSInteger i = viewControllers.count - 1; i >= 0; i--) {
                UIViewController* viewController = viewControllers[i];
                if (![viewController isKindOfClass:[self class]]) {
                    index = i;
                    break;
                }
            }
            [self.navigationController popToViewController:viewControllers[index] animated:YES];
            return;
        }
        
        if ([x integerValue] == 2) {
            //@"信息匹配中，请稍等..."弹窗，展示
            [self checkAlertView];
            return;
        }
        
        if ([x integerValue] == 3) {
            //@"信息匹配中，请稍等..."弹窗，移除
            [self.alertbgView removeFromSuperview];
            return;
        }
    }];
    
    
    [[self.viewModel.userAuthorFailCommand.executionSignals switchToLatest] subscribeNext:^(id  _Nullable x) {
        
        @strongify(self);
        
        [SVProgressHUD dismiss];
        
        //跳出申请认证界面
        NSArray *viewControllers = self.navigationController.viewControllers;
        NSUInteger index = viewControllers.count - 2;
        for (NSInteger i = viewControllers.count - 1; i >= 0; i--) {
            UIViewController* viewController = viewControllers[i];
            if (![viewController isKindOfClass:[self class]]) {
                index = i;
                break;
            }
        }
        [self.navigationController popToViewController:viewControllers[index] animated:YES];
        
    }];
    
    [[self.viewModel.freshProfileCommand.executionSignals switchToLatest] subscribeNext:^(NSNumber*  _Nullable x) {
        
        @strongify(self);
        
        [SVProgressHUD dismiss];
        
        if ([x boolValue]) {
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            //请求失败 推出登陆
            [[SEGUhomeMediator sharedInstance] seg_pushToLoginViewController:nil];
        }
    }];
}

#pragma mark - getter
-(SEGSubmitUserAtuhViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[SEGSubmitUserAtuhViewModel alloc]init];
    }
    return _viewModel;
}
#pragma mark setter
@end


@implementation SEGSubmitUserAtuhViewTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    self.titleLabel = [UILabel new];
    [self.contentView addSubview:self.titleLabel];

    self.titleLabel.textColor = kColor_1;
    self.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(15);
        make.width.mas_equalTo(60);
        make.height.equalTo(self.contentView);
        make.centerY.equalTo(self.contentView);
    }];
    
    self.titleTF = [UITextField new];
    self.titleTF.textAlignment = NSTextAlignmentRight;
    self.titleTF.textColor = kColor_1;
    self.titleTF.font = kFont_16;
    [self.contentView addSubview:self.titleTF];
    
    [self.titleTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.titleLabel);
        make.left.equalTo(self.titleLabel.mas_right).offset(10);
        make.right.equalTo(self.contentView).offset(-15);
        make.height.equalTo(self.contentView);
    }];
    
    
    self.downLine = [UIView new];
    self.downLine.backgroundColor = kColor_L2;
    [self.contentView addSubview:self.downLine];
    [self.downLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contentView);
        make.left.right.equalTo(self.contentView);
        make.height.mas_equalTo(0.5);
    }];
}

@end
